package com.dahua.ui.main;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.ViewCompat;
import android.text.Html;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.bigkoo.alertview.AlertView;
import com.bigkoo.alertview.OnItemClickListener;
import com.dahua.R;
import com.dahua.adapters.CreatedPeopleAdapter;
import com.dahua.bean.ScanResult;
import com.dahua.ui.base.BaseActivity;
import com.dahua.utils.AppApplication;
import com.dahua.utils.HttpUtils;
import com.dahua.utils.UserPreference;
import com.dahua.view.InfoDialog;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;


public class ScanPrepareUploadAct extends BaseActivity implements View.OnClickListener {
    EditText etName, etPwd;
    List<ScanResult> list = new ArrayList<ScanResult>();
    private ListView createListview;
    private CreatedPeopleAdapter adapter;

    private String flag = "0";

    boolean isSubmit;

    TextView text_upload_title;
    TextView text_load_clear, text_load_submit;
//    text_load_continue
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.prepare_upload);
        initView();
    }

    private void initView() {
        text_upload_title = findViewById(R.id.text_upload_title);
        text_load_clear = findViewById(R.id.text_load_clear);
//        text_load_continue = findViewById(R.id.text_load_continue);
        text_load_submit = findViewById(R.id.text_load_submit);

        String curr = UserPreference.getInstance(getApplicationContext()).getData();
        if (curr.contains("##")) {
            String a[] = curr.split("##");
            for (int i = 0; i < a.length; i++) {
                ScanResult bean = new ScanResult();
                bean.setContent(a[i].split("@@")[0]);
                bean.setTime(a[i].split("@@")[1]);
                if (bean.getContent().contains("http")) {
                    bean.setError("Incorrect format.");
                }
                list.add(bean);
            }
        } else if (!curr.isEmpty()) {
            ScanResult bean = new ScanResult();
            bean.setContent(curr.split("@@")[0]);
            bean.setTime(curr.split("@@")[1]);
            if (bean.getContent().contains("http")) {
                bean.setError("Incorrect format.");
            }
            list.add(bean);
        }
        createListview = (ListView) findViewById(R.id.create_listView);
        adapter = new CreatedPeopleAdapter(ScanPrepareUploadAct.this, list);
        createListview.setAdapter(adapter);

        String lang = UserPreference.getInstance(this).getLang();
        readAssetsFile(lang);
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    private Properties properties;

    private void readAssetsFile(String lang) {
        properties = new Properties();
        try {
            InputStream is = getAssets().open("part2/resources/js/lang/lang_" + lang + ".properties");
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(is));
            properties.load(bufferedReader);
        } catch (Exception e) {
            e.printStackTrace();
        }
        text_upload_title.setText(properties.getProperty("partner_Wait_to_Upload"));
        text_load_clear.setText(properties.getProperty("partner_Clear"));
////        text_load_continue.setText(properties.getProperty("partner_Continue"));
        text_load_submit.setText(properties.getProperty("partner_Submit"));
    }

    public void del(ScanResult bean, int position) {
//        List<ScanResult> list1=new ArrayList<ScanResult>();
//        for(int i=0;i<list.size();i++){
//            String content=bean.getContent();
//            String content1=list.get(i).getContent();
//            if(!content.equals(content1)){
//                list1.add(list.get(i));
//            }
//        }
//        list=list1;
        list.remove(position);
        adapter.setNearbyInfoList(list);
        adapter.notifyDataSetChanged();
        UserPreference.getInstance(getApplicationContext()).setData("");
        for (int i = 0; i < list.size(); i++) {
            String curr = UserPreference.getInstance(getApplicationContext()).getData();
            if ("".equals(curr)) {
                UserPreference.getInstance(getApplicationContext()).setData(list.get(i).getContent() + "@@" + list.get(i).getTime());
            } else {
                UserPreference.getInstance(getApplicationContext()).setData(curr + "##" + list.get(i).getContent() + "@@" + list.get(i).getTime());
            }
        }

        showToast(properties.getProperty("delete_success"));
    }

    public void login(View view) {
        if (isSubmit) {
            UserPreference.getInstance(getApplicationContext()).setData("");
        }
        AppApplication.aliveActivitys.remove(AppApplication.aliveActivitys.size() - 1);
        Intent intent1 = new Intent(this, MipcaActivityCaptureZbar.class);
        startActivity(intent1);
        if (flag.equals("1")) {
            list.clear();
            createListview.setAdapter(new CreatedPeopleAdapter(ScanPrepareUploadAct.this, list));
            UserPreference.getInstance(getApplicationContext()).setData("");
        }
        finish();
    }

    public void clear(View view) {
        list.clear();
        createListview.setAdapter(new CreatedPeopleAdapter(ScanPrepareUploadAct.this, list));
        UserPreference.getInstance(getApplicationContext()).setData("");
        showToast(properties.getProperty("clear_success"));
    }

    private Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            hideLoadingDialog();
            switch (msg.what) {
                case 1:

                        isSubmit = true;
//                    int  erroCount=0;
                        List<ScanResult> list1 = (List<ScanResult>) msg.obj;
                        for (int i = 0; i < list1.size(); i++) {
                            if ("1".equals(list1.get(i).getStatus())) {
                                for (int j = 0; j < list.size(); j++) {
                                    if (list1.get(i).getContent().equals(list.get(j).getContent())) {
                                        list.remove(j);
                                    }
                                }
                            } else {
//                            erroCount++;
                                for (int j = 0; j < list.size(); j++) {
                                    if (list1.get(i).getContent().equals(list.get(j).getContent())) {
                                        list.get(j).setError(list1.get(i).getError());
                                        list.get(j).setModel(list1.get(i).getModel());
                                    }
                                }
                            }
                        }
//                    for(int j=0;j<list.size();j++){
//                        if(list.get(j).getContent().contains("http")){
//                            erroCount++;
//                        }
//                    }
                        adapter.setNearbyInfoList(list);
                        adapter.notifyDataSetChanged();
                        if (list.size() > 0) {
                            flag = "1";
                            String notice1="";
                            String notice2="";
                            if(msg.arg2==0){
                                notice1 = properties.getProperty("submission_notice").replace("{0}", msg.arg1 + "").
                                        replace("{1}", UserPreference.getInstance(getApplicationContext()).getTotal()+ "");
                                notice2="";
                            }else{
                                notice1 = properties.getProperty("submission_notice").replace("{0}", msg.arg1 + "").
                                        replace("{1}", UserPreference.getInstance(getApplicationContext()).getTotal()+ "");
                                notice2=properties.getProperty("submission_notice1").replace("{2}", msg.arg2 + "");
                            }

                            Log.e("TAG",notice1);
                            Log.e("TAG",notice2);

                            showDialogDetail(notice1,notice2);
                            UserPreference.getInstance(getApplicationContext()).setData("");
                            for (int i = 0; i < list.size(); i++) {
                                String curr = UserPreference.getInstance(getApplicationContext()).getData();
                                if ("".equals(curr)) {
                                    UserPreference.getInstance(getApplicationContext()).setData(list.get(i).getContent() + "@@" + list.get(i).getTime());
                                } else {
                                    UserPreference.getInstance(getApplicationContext()).setData(curr + "##" + list.get(i).getContent() + "@@" + list.get(i).getTime());
                                }
                            }
                        } else {
                            String notice1="";
                            String notice2="";
                            if(msg.arg2==0){
                                notice1 = properties.getProperty("submission_notice").replace("{0}", msg.arg1 + "").
                                        replace("{1}", UserPreference.getInstance(getApplicationContext()).getTotal()+ "");
                                notice2="";
                            }else{
                                notice1 = properties.getProperty("submission_notice").replace("{0}", msg.arg1 + "").
                                        replace("{1}", UserPreference.getInstance(getApplicationContext()).getTotal()+ "");
                                notice2=properties.getProperty("submission_notice1").replace("{2}", msg.arg2 + "");
                            }

                            showDialogDetail(notice1,notice2);
                        }

                    break;
                case 2:
                    showDialog(msg.obj.toString());
                    break;
            }
        }

        ;
    };

    @Override
    protected void onPostResume() {
        super.onPostResume();
    }

    public void showDialogDetail(String content1,String content2) {
        String check_detail =  properties.getProperty("check_detail");
        String close = properties.getProperty("close");

        InfoDialog dialog =new InfoDialog(this,content1,content2,check_detail,close,R.style.MyDialog);
        dialog.show();
    }

    public void showDialog(String content) {
        new AlertView(null, "\n" + content, null, null, new String[]{"ok"}, this, AlertView.Style.Alert, null).show();
    }

    public void register(View view) {
        if (list.size() == 0) {
            showToast(properties.getProperty("no_data_submit"));
            return;
        }
        String name = "";
        for (int i = 0; i < list.size(); i++) {
            if (list.get(i).getContent().contains("http") || list.get(i).getContent().trim().length() == 0) {
                name += "";
            } else {
                name += list.get(i).getContent() + ",";
            }
        }
        String content = "";
        if (name.length() > 1) {
            showLoadingDialog();
            content = name.substring(0, name.length() - 1);
            HttpUtils.getInstance().submit(handler, content, UserPreference.getInstance(getApplicationContext()).getUid());
        } else {
            isSubmit = true;
            int erroCount = 0;
            for (int j = 0; j < list.size(); j++) {
                if (list.get(j).getContent().contains("http") || list.get(j).getContent().trim().length() == 0) {
                    erroCount++;

                    list.get(j).setError("Incorrect format.");

                }
            }
            adapter.setNearbyInfoList(list);
            adapter.notifyDataSetChanged();
            if (list.size() > 0) {
                String notice = properties.getProperty("upload_notice").replace("{0}", erroCount + "");
                showDialog(notice);

                UserPreference.getInstance(getApplicationContext()).setData("");
                for (int i = 0; i < list.size(); i++) {
                    String curr = UserPreference.getInstance(getApplicationContext()).getData();
                    if ("".equals(curr)) {
                        UserPreference.getInstance(getApplicationContext()).setData(list.get(i).getContent() + "@@" + list.get(i).getTime());
                    } else {
                        UserPreference.getInstance(getApplicationContext()).setData(curr + "##" + list.get(i).getContent() + "@@" + list.get(i).getTime());
                    }
                }
            }
        }
    }

    public void back(View view) {
        if (isSubmit) {
            UserPreference.getInstance(getApplicationContext()).setData("");
        }
        Intent intent1 = new Intent(this, MipcaActivityCaptureZbar.class);
        startActivity(intent1);
        if (flag.equals("1")) {
            list.clear();
            createListview.setAdapter(new CreatedPeopleAdapter(ScanPrepareUploadAct.this, list));
            UserPreference.getInstance(getApplicationContext()).setData("");
        }
        finish();

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            Intent intent1 = new Intent(this, MipcaActivityCaptureZbar.class);
            startActivity(intent1);
            if (flag.equals("1")) {
                list.clear();
                createListview.setAdapter(new CreatedPeopleAdapter(ScanPrepareUploadAct.this, list));
                UserPreference.getInstance(getApplicationContext()).setData("");
            }
            finish();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onStop() {
        super.onStop();
//        if (flag.equals("1")) {
//            list.clear();
//            createListview.setAdapter(new CreatedPeopleAdapter(ScanPrepareUploadAct.this, list));
//            UserPreference.getInstance(getApplicationContext()).setData("");
//        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (flag.equals("1")) {
            list.clear();
            createListview.setAdapter(new CreatedPeopleAdapter(ScanPrepareUploadAct.this, list));
            UserPreference.getInstance(getApplicationContext()).setData("");
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
        }
    }

}
